''' Copyright (c) 2006-2007, PreFab Software Inc. '''
# -*- coding: UTF-8 -*-
# Modified by aaloy in order to adapt it to the Django trunk version
# and added tranlation tags.

import datetime
from django.utils.translation import ugettext as _
from django.contrib.admin.models import LogEntry, CHANGE, ADDITION
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render_to_response
from django.contrib.auth.decorators import user_passes_test
from django.conf import settings
from django.utils.encoding import smart_unicode
from django.views.decorators.cache import never_cache
from backoffice import EntryForm
from blogmaker.util import formatChanges
from django.contrib.auth.models import User
from blogmaker.blog.models import Tag, Entry
from django.contrib.contenttypes.models import ContentType

@user_passes_test(lambda u: u.has_perm('blogmaker.entry'))
@never_cache    
def existing_entries(request):
    ''' View tools index'''
    
    sort = request.GET.get('sort', '-pub_date')
    entries = Entry.objects.all().order_by(sort)
    
    return render_to_response('blog/tools/entry_list.html', {'entries': entries, 'sort': sort})
    
    
   
@user_passes_test(lambda u: u.has_perm('blogmaker.entry'))
@never_cache
def edit_entry(request, id=None):
    ''' Edit and preview an existing entry'''
      
    # if editing existing entry  
    if id:
        entry = get_object_or_404(Entry, id=id)
        current_image = entry.image
        preview = True
        initial = dict(pub_date=entry.pub_date, headline=entry.headline, slug=entry.slug, copyright=entry.copyright,
                       body=entry.body_markdown, active=entry.active, user=entry.user_id, image=entry.image,
                       tags=[ t.id for t in entry.tags.all() ], 
                       related_entries=[ e.id for e in entry.related_entries.all() ])
    
    # if adding new entry
    else:
        entry = None
        current_image = None
        preview = False
        now = datetime.datetime.now()
        delay = datetime.timedelta(minutes=30)
        pub_date = now+delay
        initial = { 'pub_date': pub_date.strftime("%Y-%m-%d %H:%M:%S"), 
                    'active': True, 
                    'user': settings.DEFAULT_BLOG_USER}
    if request.method == 'POST':
        if not entry:
            entry = Entry()
            new_entry = True
        else:
            new_entry = False
        # validate the form, save the object, and redirect results
        new_data = request.POST.copy()
        if 'active' in new_data:
            new_data['active'] = True
        else:
            new_data['active'] = False
        
        form = EntryForm(new_data, request.FILES)
        
        if form.is_valid():
            cleaned_data = form.cleaned_data
            
            # log changes if existing entry prior to changing and saving new fields

            if not new_entry:
                changes = []
                for field in cleaned_data:
                    if field != 'related_entries' and field != 'tags' and field != 'user':
                        old_value = getattr(entry, field)
                        new_value = cleaned_data[field]
                        if field == 'body' or field == 'headline':
                            new_value = smart_unicode(new_value,'utf-8')
                            old_value = smart_unicode(old_value,'utf-8')
                    elif field == 'related_entries':
                        old_value = [ e.headline for e in entry.related_entries.all() ]
                        new_value = [ Entry.objects.get(id=id).headline for id in cleaned_data['related_entries'] ]
                    elif field == 'tags':
                        old_value = [ t.tag for t in entry.tags.all() ]
                        old_value = sorted(old_value)
                        new_value = [ Tag.objects.get(id=id).tag for id in cleaned_data['tags'] ]
                        new_value = sorted(new_value)
                    elif field == 'user':
                        old_value = getattr(entry, field)
                        new_value = User.objects.get(id=cleaned_data['user'])
                    if new_value != old_value:
                        changes.append( (entry.id, field, old_value, new_value) )
                log_changes = formatChanges('Blogmaker tools', changes)
                if changes:
                    LogEntry.objects.log_action(request.user.id, ContentType.objects.get_for_model(Entry).id,
                                                entry.id, entry.headline, CHANGE, log_changes)
            
            entry.headline = smart_unicode(cleaned_data['headline'],'utf-8')
            entry.slug = cleaned_data['slug']
            entry.pub_date = cleaned_data['pub_date']
            entry.copyright = cleaned_data['copyright']
            entry.body_markdown = smart_unicode(cleaned_data['body'],'utf-8')
            entry.active = cleaned_data['active']
            entry.user_id = cleaned_data['user']
            entry.save()  # save prior to adding M2M fields which require a pk
            entry.tags = cleaned_data['tags']
            entry.related_entries = cleaned_data['related_entries']
            entry.externalId = cleaned_data['externalId']

            if cleaned_data['image']:            
                entry.save_image_file(cleaned_data['image'].filename, cleaned_data['image'].content)
            
            entry.save()
            
            # log if new entry after saving the entry and filling all fields
            if new_entry:
                changes = []
                for field in cleaned_data:
                    if field != 'related_entries' and field != 'tags' and field != 'user':
                        new_value = cleaned_data[field]
                        if field == 'body' or field == 'headline':
                            new_value = smart_unicode(new_value,'utf-8')
                    elif field == 'related_entries':
                        new_value = [ Entry.objects.get(id=id).headline for id in cleaned_data['related_entries'] ]
                    elif field == 'tags':
                        new_value = [ Tag.objects.get(id=id).tag for id in cleaned_data['tags'] ]
                    elif field == 'user':
                        new_value = User.objects.get(id=cleaned_data['user'])
                    changes.append( (entry.id, field, 'NEW ENTRY', new_value) )
                log_changes = formatChanges('Blogmaker tools', changes)
                LogEntry.objects.log_action(request.user.id, ContentType.objects.get_for_model(Entry).id,
                                            entry.id, entry.headline, ADDITION, log_changes)
            
            # redirect to the same page with preview or to the entries list
            if request.POST.has_key('preview'):
                this_entry = '%stools/entry/%s/' % (settings.BLOG_ROOT, entry.id)
                return HttpResponseRedirect(this_entry)
            if request.POST.has_key('close'):
                all_entries = '%stools/entry/' % settings.BLOG_ROOT
                return HttpResponseRedirect(all_entries)
        else:
            return render_to_response('blog/tools/edit_entry.html', {'form': form, 'object': entry, 'preview': False}) 
    	
    else:
        form = EntryForm(initial=initial)
        return render_to_response('blog/tools/edit_entry.html', {'form': form, 
                                                                'object': entry, 
                                                                'preview': preview, 
                                                                'current_image': current_image})
